package indi.mozping.concurrentutil.cyclicbarrierp;

import indi.mozping.tools.SleepTools;

import java.util.concurrent.CyclicBarrier;

/**
 * @author by mozping
 * @Classname CyclicBarrierTest
 * @Description ͨ��CyclicBarrier������һ���̵߳���ָ����֮����ִ�������Ĳ���
 * ���ﶨ����MyWorkBeforeThread�̣߳���ʾ����ǰ�ڴ���MyWorkAfterThread��ʾ������ڴ���
 * ������3��ǰ�ڴ����̣߳���Ҫ3���̶߳�����ĳ����֮��MyWorkAfterThread�̲߳��ܼ�������
 * �۲������֣������̻߳���await���໥�ȴ��������MyWorkAfterThread�߳̾ͻ�ִ�У�
 * ����ĳ�ʼ������new CyclicBarrier(3, new MyWorkAfterThread());3�����������߳���Ҫ�������ϵ㣬
 * MyWorkAfterThread��ʾ�������ϵ���ִ�е��̣߳�����ע�������3���̵߳��������߳�ֻ������2���̣߳�
 * ��ô���ϵ������һֱ���ܱ����㣬�̻߳���await��������MyWorkAfterThread�߳�һֱ���ᱻ����
 * @Date 2019/1/2 16:29
 */
public class CyclicBarrierTest {

    //3��ʾ��Ҫ�������ϵ���߳�������MyWorkAfterThread��ʾ�������ϵ����Ҫִ�е�����
    //private static CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new MyWorkAfterThread());
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(3);


    private static class MyWorkBeforeThread extends Thread {
        @Override
        public void run() {
            System.out.println("ҵ��Before�߳� [" + Thread.currentThread().getName() + "] ����ҵ��...");
            //�������10���ڵ�ʱ��
            try {
                SleepTools.randomMs(2000);
                System.out.println("ҵ��Before�߳� [" + Thread.currentThread().getName() + "�������ϵ���߳�����" + (cyclicBarrier.getNumberWaiting()));
                int i = cyclicBarrier.await();
                System.out.println("ҵ��Before�߳� [" + Thread.currentThread().getName() + "] ����դ���ı����: " + i);
                System.out.println("ҵ��Before�߳� [" + Thread.currentThread().getName() + "] �ȴ����..." + System.currentTimeMillis());
            } catch (Exception e) {
                e.printStackTrace();
            }
            SleepTools.randomSecond(10);
            System.out.println("ҵ��Before�߳� [" + Thread.currentThread().getName() + "] ��������������..." + System.currentTimeMillis());
        }
    }

    private static class MyWorkAfterThread extends Thread {
        @Override
        public void run() {
            System.out.println("ҵ��After�߳� [" + Thread.currentThread().getName() + "] ����..." + System.currentTimeMillis());
        }
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            new MyWorkBeforeThread().start();
        }
    }
}
